package user.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import user.entity.User;
import user.service.IUserService;
import user.web.base.BaseController;
import user.web.base.BaseResp;
import user.web.base.ErrorCode;
import user.web.center.VerifyCodeCenter;
import user.web.exception.ErrorCodeException;
import user.web.utils.RandomUtils;
import user.web.utils.SendCode;
import user.web.vo.LoginReq;
import user.web.vo.RegistReq;
import user.web.vo.UpdateInfoReq;
import user.web.vo.ValidPhoneReq;

/**
 *
 * @author Eric
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	IUserService userService;
	
	private Map<String, String> phoneMapCode = VerifyCodeCenter.phoneMapVerifyCode;
	
	@RequestMapping("/regist")
	public BaseResp regist(@RequestBody RegistReq req) {
		
		String phone = req.getPhone();
		String password = req.getPassword();
		String verifyCode = req.getCode();
		
		if(!phoneMapCode.get(phone).equals(verifyCode)) {
			return failure("手机验证码错误");
		}
		userService.regist(phone, password);
		return OK;
	}

	@RequestMapping("/phoneValid")
	public BaseResp phoneValid(@RequestBody ValidPhoneReq req) {
		/** 请求验证码  验证码的时效性由前端控制*/
		String verifyCode = RandomUtils.generateVerifyCode();
		SendCode.sendMessage(req.getPhone(), verifyCode);
		phoneMapCode.put(req.getPhone(), verifyCode);
		return OK;
	}
	
	@RequestMapping("/login")
	public BaseResp login(HttpServletRequest request, @RequestBody LoginReq req) {
		
		String phone = req.getPhone();
		String password = req.getPassword();
		User user = userService.login(phone, password);
		if(user == null) {
			throw new ErrorCodeException(ErrorCode.BAD_REQUEST, "用户不存在");
		}
		return success(user);
	}

	@RequestMapping("/logout")
	public BaseResp logout(HttpServletRequest request) {
		
		return OK;
	}
	
	@RequestMapping("/userInfo")
	public BaseResp userInfo(HttpServletRequest request){
		
		return OK;
	}
	
	@RequestMapping("/update")
	public BaseResp update(HttpServletRequest request, @RequestBody UpdateInfoReq req){
		
		return OK;
	}
	
	
	
}
